package main

import (
	"flag"
	"fmt"
	"go_final/mxshop_srvs/goods_srv/global"
	"go_final/mxshop_srvs/goods_srv/handler"
	"go_final/mxshop_srvs/goods_srv/initialize"
	goodspb "go_final/mxshop_srvs/goods_srv/proto/protofile"
	"go_final/mxshop_srvs/goods_srv/utils"
	"net"
	"os"
	"os/signal"
	"syscall"

	"github.com/hashicorp/consul/api"

	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"

	"go.uber.org/zap"

	uuid "github.com/satori/go.uuid"
	"google.golang.org/grpc"
)

func main() {
	// 2.初始化logger
	initialize.InitLogger()

	// 1.初始化配置文件
	initialize.InitConfig()

	// 3.初始化数据库
	initialize.InitDB()

	// 4.初始化ES
	initialize.InitEs()

	IP := flag.String("ip", "0.0.0.0", "ip地址")
	Port := flag.Int("port", 0, "端口号")
	flag.Parse()
	if *Port == 0 {
		var err error
		*Port, err = utils.GetFreePort()
		if err != nil {
			// 没有找到可用端口
			panic(err)
		}
	}
	zap.S().Info("*Port ", *Port)

	s := grpc.NewServer()

	goodspb.RegisterGoodsServer(s, &handler.Server{})
	lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *IP, *Port))
	if err != nil {
		panic(err)
	}

	// 注册服务健康检查
	grpc_health_v1.RegisterHealthServer(s, health.NewServer())
	cfg := api.DefaultConfig()
	cfg.Address = fmt.Sprintf("%s:%d", global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port)

	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}

	// 配置检查项
	check := &api.AgentServiceCheck{
		GRPC:                           fmt.Sprintf("%s:%d", "192.168.4.170", *Port),
		Timeout:                        "5s",
		Interval:                       "5s",
		DeregisterCriticalServiceAfter: "10s",
	}

	// 生成注册对象
	registration := new(api.AgentServiceRegistration)
	registration.Name = global.ServerConfig.Name
	// 通过uuid随机生成服务id
	serviceID := fmt.Sprintf("%s", uuid.NewV4())
	registration.ID = serviceID
	registration.Tags = global.ServerConfig.Tags
	registration.Address = "192.168.4.170"
	registration.Port = *Port
	registration.Check = check
	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		panic(err)
	}

	go func() {
		err = s.Serve(lis)
		if err != nil {
			panic(err)
		}
	}()

	// 接收终止信号
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	<-quit
	if err = client.Agent().ServiceDeregister(serviceID); err != nil {
		zap.S().Info("注销服务失败")
	} else {
		zap.S().Info("注销服务成功")
	}
}
